package com.revzone.demo001.PermissionModule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.revzone.demo001.LogModule.aspect.OperationLog;
import com.revzone.demo001.PermissionModule.mapper.UserAndRoleMapper;
import com.revzone.demo001.PermissionModule.mapper.UserMapper;
import com.revzone.demo001.PermissionModule.service.UserService;
import com.revzone.demo001.entity.ExciptionEntity.AppException;
import com.revzone.demo001.entity.OtherEntity.PageResult;
import com.revzone.demo001.entity.OtherEntity.R;
import com.revzone.demo001.entity.PermissionEntity.User;
import com.revzone.demo001.entity.PermissionEntity.UserAndRole;
import com.revzone.demo001.entity.PermissionEntity.UserRoleDTO;
import com.revzone.demo001.enums.ExciptionEnums.EnumExciption;
import com.revzone.demo001.enums.PermissionEnums.EnumOperationLog;
import com.revzone.demo001.enums.PermissionEnums.EnumTypeValue;
import com.revzone.demo001.utils.JwtUtils.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 * @author lsa
 * @since 2023-03-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

   @Autowired
   UserMapper userMapper;
   @Autowired
   UserAndRoleMapper userAndRoleMapper;

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.USER_LOGIN_MSG)
    public R getReUser(User user) {
        HashMap<String, Object> map = new HashMap<>();
        List<User> list = userMapper.getReUser(user.getUserName());
        if (list == null || list.size() == 0){
            logger.error(EnumExciption.AUTH_REQUEST_EXISTS.getMsg());
            throw new AppException(EnumExciption.AUTH_REQUEST_EXISTS);
        }
        String realPassword = (String) list.get(0).getPassword();
        if (realPassword == null) {
            logger.error(EnumExciption.AUTH_REQUEST_EXISTS.getMsg());
            throw new AppException(EnumExciption.AUTH_REQUEST_EXISTS);
//            return R.error("用户名错误");
        } else if (!realPassword.equals(user.getPassword())) {
            logger.error(EnumExciption.AUTH_REQUEST_ERROR.getMsg());
            throw new AppException(EnumExciption.AUTH_REQUEST_ERROR);
//            return R.error( 401,"密码错误");
        } else if (list.get(0).getStatus() == 1) {
            logger.error(EnumExciption.AUTH_REQUEST_LOCKED.getMsg());
            throw new AppException(EnumExciption.AUTH_REQUEST_LOCKED);
        } else {
            map.put("token", JWTUtil.createToken(user.getUserName()));
            map.put("info",list.get(0));
//            HashMap<String, Object> map1 = new HashMap<>();
//            map1.put("list",list.get(0));
//            map1.put("Token",JWTUtil.createToken(user.getUsername()));
//            map.put("data",map1);
            return R.ok(map);
        }
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.USER_REFRESH)
    public R getReUserRefresh(String userName) {
        HashMap<String, Object> map = new HashMap<>();
        List<User> list = userMapper.getReUser(userName);
        if (list == null || list.size() == 0){
            logger.error(EnumExciption.AUTH_REQUEST_EXISTS.getMsg());
            throw new AppException(EnumExciption.AUTH_REQUEST_EXISTS);
        }
        String realPassword = (String) list.get(0).getPassword();
        if (realPassword == null) {
            logger.error(EnumExciption.AUTH_REQUEST_EXISTS.getMsg());
            throw new AppException(EnumExciption.AUTH_REQUEST_EXISTS);
//            return R.error("用户名错误");
        } else if (list.get(0).getStatus() == 1) {
            logger.error(EnumExciption.AUTH_REQUEST_LOCKED.getMsg());
            throw new AppException(EnumExciption.AUTH_REQUEST_LOCKED);
        } else {
            map.put("info",list.get(0));
            return R.ok(map);
        }
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.USER_LIST_PAGE_MSG)
    public R getUserListPage(UserRoleDTO userRoleDTO) {

        HashMap<String, Object> map = new HashMap<>();
        PageResult<User> result = null;
        try {
            List<User> userList = userMapper.getReFindBy(userRoleDTO);

            // 对结果集进行分页处理，并返回指定页码的数据
            Long pageSize = userRoleDTO.getPageSize();      // 每页显示的数据条数
            Long currentPage = userRoleDTO.getCurrentPage();    // 当前页码，假设为第二页
            long totalPages = (long) Math.ceil((double) userList.size() / pageSize);//总记录数
            long total = userList.size();

            Long startIndex = (currentPage - 1) * pageSize;
            Long endIndex = currentPage * pageSize;
            List<User> pageData = userList.subList(Math.toIntExact(startIndex), Math.toIntExact(Math.min(endIndex, userList.size())));;
            for (User user :pageData) user.setPassword(null);
            result = new PageResult<>(pageData, pageSize, currentPage, totalPages, total);

            // 封装自定义分页查询结果
//            Page<User> page = new Page<>(userRoleDTO.getCurrentPage(),userRoleDTO.getPageSize());
//            IPage<User> findByPage = userMapper.getReFindByPage(page, userRoleDTO);
//            result = new PageResult<User>(findByPage);

        } catch (Exception e) {
            throw new AppException("用户分页查询失败！");
        }
        map.put("data",result);
        return R.ok(map);
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.USER_INSERT_MSG)
    public R setUserList(UserRoleDTO userRoleDTO) {
        int insert = 0;
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",userRoleDTO.getUserName());
        User old_user = userMapper.selectOne(wrapper);
        if (old_user != null){
            throw new AppException("重复用户名！");
        }
        try {
            User user = new User();
            BeanUtils.copyProperties(userRoleDTO, user);
            user.setCreateDate(new Date());
            user.setUpdateDate(new Date());
            insert = userMapper.insert(user);

            if(userRoleDTO.getRoleId() != null){
                for (Integer integer : userRoleDTO.getRoleId()) {
                    userAndRoleMapper.insert(new UserAndRole(user.getId(),integer));
                }
            }
        } catch (Exception e) {
            throw new AppException("新增用户失败！");
        }

        if (insert != 0){
            return R.ok("success");
        }else {
            return R.error("Failure");
        }
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.USER_UPDATE_MSG)
    public R updateUserList(UserRoleDTO userRoleDTO) {
        int update = 0;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userRoleDTO.getUserName());
        User old_user = userMapper.selectById(userRoleDTO.getId());
        if (!old_user.getUserName().equals(userRoleDTO.getUserName())
                && userMapper.selectOne(queryWrapper) != null) {
            throw new AppException("重复用户名！");
        }

        try {
            User user = new User();
            BeanUtils.copyProperties(userRoleDTO, user);
            if(user.getPassword() == null || user.getPassword() == ""){
                user.setPassword(old_user.getPassword());
            }
            user.setUpdateDate(new Date());
            update = userMapper.updateById(user);

            if(userRoleDTO.getRoleId() != null){
                //先删除
                int delete = 0;
                try {
                    QueryWrapper<UserAndRole> wrapper = new QueryWrapper<>();
                    wrapper.eq("user_id",userRoleDTO.getId());
                    delete = userAndRoleMapper.delete(wrapper);
                } catch (Exception e) {
                    throw new AppException(e.getMessage());
                }
                //后新增
                for (Integer integer : userRoleDTO.getRoleId()) {
                    userAndRoleMapper.insert(new UserAndRole(userRoleDTO.getId(),integer));
                }
            }else {
                //直接删除
                QueryWrapper<UserAndRole> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",userRoleDTO.getId());
                int delete = userAndRoleMapper.delete(wrapper);
            }

        } catch (Exception e) {
            throw new AppException("修改用户失败！");
        }

        if (update != 0){
            return R.ok("success");
        }else return R.error("Failure");

    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.USER_DEL_MSG)
    public R delUserList(Integer id) {
        try {
            if(id != 0 && id != null){
                QueryWrapper<UserAndRole> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",id);
                userAndRoleMapper.delete(wrapper);

                int i = userMapper.deleteById(id);
                if (i != 0){
                    return R.ok("success");
                }else return R.error("Failure");

            }
        } catch (Exception e) {
            throw new AppException("删除用户户失败！");
        }

        return null;
    }




//    public R getUserListPage1(User user) {
//        HashMap<String, Object> map = new HashMap<>();
//        // 创建分页对象】
////        Page<Map<String,Object>> page = new Page<>(user.getCurrentPage(),user.getPageSize());
//        Page<User> page = new Page<>(user.getCurrentPage(),user.getPageSize());
//        // 构建查询条件
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//
////        QueryWrapper<User> wrapper = BaseEntity.getQueryWrapper(user);
////        if (!(user.getSex() == null)) {
////            wrapper.like("sex", user.getSex());
////        } else if (!(user.getStatus() == null)) {
////            wrapper.like("status", user.getStatus());
////        }
//
//
//        if (StringUtils.isNotEmpty(user.getUserName())) {
//            wrapper.like("user_name", user.getUserName());
//        } else if (StringUtils.isNotEmpty(user.getNickName())) {
//            wrapper.like("nick_name", user.getNickName());
//        } else if (!(user.getSex() == null)) {
//            wrapper.like("sex", user.getSex());
//        } else if (StringUtils.isNotEmpty(user.getPhone())) {
//            wrapper.like("phone", user.getPhone());
//        } else if (StringUtils.isNotEmpty(user.getEmail())) {
//            wrapper.like("email", user.getEmail());
//        } else if (!(user.getStatus() == null)) {
//            wrapper.like("status", user.getStatus());
//        }
//
//        // 执行分页查询selectPage(page, wrapper)
////        IPage<Map<String,Object>> userPage = userMapper.selectMapsPage(page, wrapper);
//        IPage<User> userPage = userMapper.selectPage(page, wrapper);
//
//        //自定义日期格式转换
////        DateConversionUtil.LocalDateTimeToDate(userPage.getRecords());
//        // 封装自定义分页查询结果
////        PageResult<Map<String,Object>> result = new PageResult<>(userPage);
//        PageResult<User> result = new PageResult<User>(userPage);
//
//        map.put("data",result);
//        return R.ok(map);
//    }
}
